package com.langhua.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.langhua.common.R;
import com.langhua.entity.User;
import com.langhua.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


@RestController
@RequestMapping("/users")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     * @param request
     * @param user
     * @return
     */
    @PostMapping("/login")
    public R<User> login(HttpServletRequest request, @RequestBody User user){

        System.out.println("user+login:"+user);
//        1、将页面提交的密码password进行md5加密处理
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));


        //2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,user.getUsername());
        User emp = userService.getOne(queryWrapper);

        System.out.println("user+登录搜索结果:"+emp);

        //3、如果没有查询到则返回登录失败结果
        if(emp == null){
            return R.error("账号不存在！登录失败");
        }

        //4、密码比对，如果不一致则返回登录失败结果
        if(!emp.getPassword().equals(user.getPassword())){
            return R.error("密码不正确！登录失败");
        }

        //5、查看会员状态，如果为已禁用状态，则返回会员已禁用结果
        if("false".equals(emp.getStatus())){
            return R.error("账号已禁用");
        }

        //6、登录成功，将会员id存入Session并返回登录成功结果
//        request.getSession().setAttribute("user",emp.getId());

        return R.success(emp,"登录成功!");
    }

    /**
     * 用户退出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        //清理Session中保存的当前登录会员的id
        request.getSession().removeAttribute("user");
        return R.success(null,"退出成功");
    }

    /**
     * 会员信息展示
     * @param current  当前页
     * @param size     每页条数
     * @param user   条件查询
     * @return
     */
    @GetMapping("{current}/{size}")
    public R<IPage> getPage(@PathVariable Integer current,@PathVariable Integer size,User user){

        IPage page=new Page(current,size);
        LambdaQueryWrapper<User> lqw=new LambdaQueryWrapper<User>();
//        lqw.eq(User::getStatus,1);
        lqw.like(Strings.isNotEmpty(user.getName()),User::getName,user.getName());

        IPage page1 = userService.page(page,lqw);
        System.out.println("管理员分页查询内容："+page1.toString());
        return R.success(page1,"admin分页查询");
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @PostMapping("/add")
    public R<String> save(@RequestBody User user){

        //添加Lambda表达式
        LambdaQueryWrapper<User> lqw =new LambdaQueryWrapper<>();
        lqw.eq(Strings.isNotEmpty(user.getUsername()),User::getUsername,user.getUsername());

        //根据username查询数据库是否存在该账号信息
        List<User> list = userService.list(lqw);
        if (list.size()>0){
            //如果存在则响应失败内容
            return R.error("账号已存在");
        }

        //用户不存在,则将页面密码进行md5加密处理
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));

        //添加数据库
        userService.save(user);

        //返回响应成功内容
        return R.success(null,"新增会员成功");
    }

    /**
     * 根据id查询会员信息 (修改数据回显)
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<User> getById(@PathVariable Long id){
        log.info("根据id查询会员信息..."+id);
        User user = userService.getById(id);
        if(user != null){
            return R.success(user,null);
        }
        return R.error("没有查询到对应会员信息");
    }

    /**
     * 根据id修改会员信息()
     * @param user
     * @return
     */
    @PutMapping
    public R<User> update(HttpServletRequest request,@RequestBody User user){
        log.info(user.toString());

        long id = Thread.currentThread().getId();
        log.info("修改id为：{}",id);
        //Long empId = (Long)request.getSession().getAttribute("admin");
        //admin.setUpdateTime(LocalDateTime.now());
        //admin.setUpdateUser(empId);

        userService.updateById(user);

        return R.success(user,"会员信息修改成功");
    }

    /**
     * 通过id删除User
     * @param id
     * @return
     */
    @DeleteMapping("{id}")
    public R<String> deleteById(@PathVariable Long id){
        log.info("删除User的id为：{}", id);

        userService.removeById(id);
        return R.success(null,"删除成功！");
    }

    /**
     * 通过id修改用户账号状态
     * @return
     */
    @PutMapping("/updateUsertStatus")
    public R updateStudentStatus(@RequestBody User user){
        boolean b = userService.updateById(user);
        if (b){
            return R.success(user,"通过id修改用户账号状态成功");
        }else {
            return R.error("通过id修改用户账号状态失败！");
        }
    }


    /**
     * 统计注册人数
     *
     * @return
     */
    @GetMapping("/getTatol")
    public R<Integer> getTatol(){
        int count = userService.count();

        return R.success(count,"统计注册人数");
    }
}
